import axios from "axios";
import TokenGoThrough from "./releaseRouter";
import { ZIp } from "./setup";
// const setupData = import.meta.env
const axiosServer = axios.create({
    baseURL: ZIp,
    timeout: 8000,
});

// Request Interceptor
axiosServer.interceptors.request.use(
    (config) => {
        if (TokenGoThrough.indexOf(config.url) !== -1) {
            return config;
        }
        let token = localStorage.getItem("token");
        if (token) {
            config.headers["Authorization"] = token;
        }
        return config;
    },
    (error) => {
        // Handle request error
        return Promise.reject(error);
    }
);

// Response Interceptor
axiosServer.interceptors.response.use(
    function (response) {
        const token = response.headers["authorization"];
        if (token) {
            localStorage.setItem("TOKEN", token);
        }
        if (response.data.code === 401) {
            alert("Login session expired, please log in again!");
            localStorage.clear();
            // Redirect to login page
            window.location.href = "/";
            return;
        }
        return response.data;
    },
    function (error) {
        // Handle response error
        return Promise.reject(error);
    }
);

export default axiosServer;